package cn.sfrog.project.biz.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizMessageConversation;
import cn.sfrog.project.biz.admin.domain.BizMessageLog;
import cn.sfrog.project.biz.admin.domain.vo.BizMessageLogFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizMessageLogQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizMessageLogVO;
import cn.sfrog.project.biz.admin.mapper.BizMessageLogMapper;
import cn.sfrog.project.biz.admin.service.IBizMessageLogService;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/**
 * 聊天消息记录Service业务层处理
 */
@Service
public class BizMessageLogServiceImpl extends ServiceImpl<BizMessageLogMapper, BizMessageLog> implements IBizMessageLogService {
    @Resource
    private BizMessageLogMapper bizMessageLogMapper;


    /**
     * 查询聊天消息记录
     *
     * @param id 聊天消息记录主键
     * @return 聊天消息记录
     */
    @Override
    public BizMessageLogVO selectBizMessageLogById(Long id) {
        return bizMessageLogMapper.selectBizMessageLogById(id);
    }

    /**
     * 查询聊天消息记录列表
     *
     * @param query 聊天消息记录
     * @return 聊天消息记录
     */
    @Override
    public List<BizMessageLogVO> selectBizMessageLogList(BizMessageLogQueryVO query) {
        List<BizMessageLogVO> bizMessageLogVOS = bizMessageLogMapper.selectBizMessageLogList(query);
        if(CollectionUtil.isNotEmpty(bizMessageLogVOS)){
            bizMessageLogVOS.sort(Comparator.comparing(BizMessageLogVO::getCreateTime));
        }
        return bizMessageLogVOS;
    }

    /**
     * 新增聊天消息记录
     *
     * @param form 聊天消息记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizMessageLog(BizMessageLogFormVO form) {
        BizMessageLog bizMessageLog = new BizMessageLog();
        BeanUtils.copyProperties(form, bizMessageLog);
        bizMessageLog.setCreateTime(new Date());
        bizMessageLog.setCreateBy(SecurityUtils.getUsername());
        bizMessageLog.setUpdateTime(new Date());
        bizMessageLog.setUpdateBy(SecurityUtils.getUsername());
        return bizMessageLog.insert();
    }

    /**
     * 修改聊天消息记录
     *
     * @param form 聊天消息记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizMessageLog(BizMessageLogFormVO form) {
        BizMessageLog bizMessageLog = new BizMessageLog();
        BeanUtils.copyProperties(form, bizMessageLog);
        bizMessageLog.setUpdateTime(new Date());
        bizMessageLog.setUpdateBy(SecurityUtils.getUsername());
        return bizMessageLog.updateById();
    }

    /**
     * 批量删除聊天消息记录
     *
     * @param ids 需要删除的聊天消息记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizMessageLogByIds(Long[] ids) {
            return BizMessageLog.DAO.delete(Wrappers.lambdaQuery(BizMessageLog.class).in(BizMessageLog::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
        //return BizMessageLog.DAO.update(Wrappers.lambdaUpdate(BizMessageLog.class).in(BizMessageLog::getId, (Object[]) vo.getIds()).set(BizMessageLog::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean setMessageRead(Long messageId) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId().toString();
        BizMessageLog bizMessageLog = BizMessageLog.DAO.selectById(messageId);
        bizMessageLog.setReadStatus(BizMessageLog.READ_STATUS_YES);
        bizMessageLog.setUpdateTime(DateUtils.getNowDate());
        bizMessageLog.setUpdateBy(userId);
        boolean update = bizMessageLog.updateById();
        if(update){
            //将会话列表的未读数量 - 1
            BizMessageConversation conversation = BizMessageConversation.DAO.selectById(bizMessageLog.getConversationId());
            if(conversation.getSendUserId().equals(bizMessageLog.getReceiveUserId())){
                if(conversation.getSendUnreadCount() > 0){
                    conversation.setSendUnreadCount(conversation.getSendUnreadCount() - 1);
                }
            }else if(conversation.getReceiveUserId().equals(bizMessageLog.getReceiveUserId())){
                if(conversation.getReceiveUnreadCount() > 0){
                    conversation.setReceiveUnreadCount(conversation.getReceiveUnreadCount() - 1);
                }
            }
            conversation.setUpdateTime(DateUtils.getNowDate());
            conversation.setUpdateBy(userId);
            conversation.updateById();
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean setMessageReadByConversationId(Long conversationId) {
        BizMessageConversation conversation = BizMessageConversation.DAO.selectById(conversationId);
        if(StringUtils.isNull(conversation)){
            throw new ApiException("会话不存在");
        }
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        if(conversation.getSendUserId().equals(userId)){
            conversation.setSendUnreadCount(0);
        }else if (conversation.getReceiveUserId().equals(userId)){
            conversation.setReceiveUnreadCount(0);
        }
        conversation.setUpdateBy(userId.toString());
        conversation.setUpdateTime(DateUtils.getNowDate());
        boolean update = conversation.updateById();
        if(update){
            LambdaQueryWrapper<BizMessageLog> lambdaQueryWrapper = new LambdaQueryWrapper<BizMessageLog>()
                    .eq(BizMessageLog::getConversationId,conversationId)
                    .eq(BizMessageLog::getReadStatus,BizMessageLog.READ_STATUS_NO)
                    .eq(BizMessageLog::getReceiveUserId,userId);
            List<BizMessageLog> messageLogList = BizMessageLog.DAO.selectList(lambdaQueryWrapper);
            List<BizMessageLog> updateList = new ArrayList<>();
            BizMessageLog updateEntity = new BizMessageLog();
            for (BizMessageLog messageLog:messageLogList) {
                updateEntity.setId(messageLog.getId());
                messageLog.setReadStatus(BizMessageLog.READ_STATUS_YES);
                messageLog.setUpdateBy(userId.toString());
                messageLog.setUpdateTime(DateUtils.getNowDate());
                updateList.add(messageLog);
            }
            if(CollectionUtil.isNotEmpty(updateList)){
                this.updateBatchById(updateList,updateList.size());
            }

        }
        return update;
    }
}
